package hi.system;

import hi.RectangleListener;

import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;

public class MouseFrame extends JFrame implements ComponentListener {

	List<RectangleListener> rectangleListeners = new ArrayList<RectangleListener>();

	public MouseFrame(String title) {
		super(title);
		addComponentListener(this);

		try {
			Class<?> awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
			Method mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
			mSetWindowOpacity.invoke(null, this, Float.valueOf(0.7f));
		} catch (NoSuchMethodException ex) {
			ex.printStackTrace();
		} catch (SecurityException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		} catch (IllegalAccessException ex) {
			ex.printStackTrace();
		} catch (IllegalArgumentException ex) {
			ex.printStackTrace();
		} catch (InvocationTargetException ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public void componentResized(ComponentEvent e) {
		handleBoundsChange(e);
	}

	@Override
	public void componentMoved(ComponentEvent e) {
		handleBoundsChange(e);
	}

	public void addRectangleListener(RectangleListener listener) {
		rectangleListeners.add(listener);
	}

	public void removeRectangleListener(RectangleListener listener) {
		rectangleListeners.remove(listener);
	}

	//WARNING: This is very light-weight and basic. If it multiple listeners are actually used,
	//a proper event production scheme should be employed.
	private void alertListeners(Rectangle rect) {
		for(RectangleListener listener : rectangleListeners) {
			listener.setRectangle(rect);
		}
	}

	@Override
	public void componentHidden(ComponentEvent arg0) {}

	@Override
	public void componentShown(ComponentEvent arg0) {}

	private void handleBoundsChange(ComponentEvent e) {
		Rectangle windowRect = e.getComponent().getBounds();
		alertListeners(windowRect);
		//System.out.println(e.getComponent().getBounds());
	}
}
